package com.imooc.converter;

import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;
import com.imooc.dataobject.OrderDetail;
import com.imooc.dto.OrderDto;
import com.imooc.enums.ResultEnum;
import com.imooc.exception.SellException;
import com.imooc.form.OrderForm;
import lombok.extern.slf4j.Slf4j;

import java.util.ArrayList;
import java.util.List;

/**
 * 功能描述: <br>
 * <p>
 * (订单实体转为订单数据传输实体)
 *
 * @Author:Mr. xyb
 * @Date: 2018/5/18 16:55
 * @since: 1.8.0
 * @version: 1.0.0
 */
@Slf4j
public class OrderForm2OrderDTOConverter {

    /**
     * 订单表单转换
     *
     * @param orderForm
     * @return
     */
    public static OrderDto convert(OrderForm orderForm) {
        Gson gson = new Gson();
        OrderDto orderDTO = new OrderDto();

        // 被转换对象的值设置到转换对象中
        orderDTO.setBuyerName(orderForm.getName());
        orderDTO.setBuyerPhone(orderForm.getPhone());
        orderDTO.setBuyerAddress(orderForm.getAddress());
        orderDTO.setBuyerOpenid(orderForm.getOpenid());

        // 把Json字符串的商品信息转换为list
        List<OrderDetail> orderDetailList = new ArrayList<>();
        try {
            orderDetailList = gson.fromJson(orderForm.getItems(),
                    new TypeToken<List<OrderDetail>>() {
                    }.getType());
        } catch (Exception e) {
            log.error("【对象转换】错误, string={}", orderForm.getItems());
            throw new SellException(ResultEnum.PARAM_ERROR);
        }
        // 把订单详情设置到转换的对象中
        orderDTO.setOrderDetailList(orderDetailList);

        return orderDTO;
    }
}
